import time

import requests
import datetime


class JDTime(object):
    def __init__(self):
        self._jdtime = datetime.datetime.now()

    def get_jd_time(self):
        url = 'https://sgm-m.jd.com'
        stime = time.time()
        r = requests.get(url)
        etime = time.time()
        print("耗时:{}MS".format(int((etime - stime) * 1000)))
        js = r.json()
        timestamp: str = js.get("timestamp")
        timestamp = timestamp.replace("T", " ")
        timestamp = timestamp.replace("+00:00", "")
        self._jdtime = datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S.%f")
        self._jdtime = self._jdtime + datetime.timedelta(hours=8)
        return self._jdtime

    def get_local_time_diff(self):
        local_time = time.time()
        self.get_jd_time()
        print("本地时间：{}".format(local_time))
        print("服务时间：{}".format(self._jdtime.timestamp()))
        print("京东时差：{}MS".format(int((self._jdtime.timestamp() - local_time) * 1000)))


if __name__ == '__main__':
    jd_time = JDTime()
    jd_time.get_local_time_diff()
